<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="UNIX,C," />





  <link rel="alternate" href="/atom.xml" title="JOE'S BLOG" type="application/atom+xml" />






<meta name="description" content="前言UNIX一切皆文件，掌握文件的操作尤其重要。以下的内容主要是apue上面第五章内容，介绍了标准I/O库的一些内容。  流和FILE对象标准I/O库，他们的操作都是围绕流进行的字符分为单字节和多字节，流的定向决定了是所读、写的字符是单字节还是多字节的。当一个流被创建时，并没有定向。使用多字节I/O函数，流的定向就被设置为宽定向，单字节同理。只有两个函数可以改变流的定向，freopen和fwide">
<meta name="keywords" content="UNIX,C">
<meta property="og:type" content="article">
<meta property="og:title" content="标准I&#x2F;O库(五)">
<meta property="og:url" content="https://joewt.com/2018/02/04/std-IO/index.html">
<meta property="og:site_name" content="JOE&#39;S BLOG">
<meta property="og:description" content="前言UNIX一切皆文件，掌握文件的操作尤其重要。以下的内容主要是apue上面第五章内容，介绍了标准I/O库的一些内容。  流和FILE对象标准I/O库，他们的操作都是围绕流进行的字符分为单字节和多字节，流的定向决定了是所读、写的字符是单字节还是多字节的。当一个流被创建时，并没有定向。使用多字节I/O函数，流的定向就被设置为宽定向，单字节同理。只有两个函数可以改变流的定向，freopen和fwide">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2018-02-14T12:35:48.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="标准I&#x2F;O库(五)">
<meta name="twitter:description" content="前言UNIX一切皆文件，掌握文件的操作尤其重要。以下的内容主要是apue上面第五章内容，介绍了标准I/O库的一些内容。  流和FILE对象标准I/O库，他们的操作都是围绕流进行的字符分为单字节和多字节，流的定向决定了是所读、写的字符是单字节还是多字节的。当一个流被创建时，并没有定向。使用多字节I/O函数，流的定向就被设置为宽定向，单字节同理。只有两个函数可以改变流的定向，freopen和fwide">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://joewt.com/2018/02/04/std-IO/"/>





  <title>标准I/O库(五) | JOE'S BLOG</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">JOE'S BLOG</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">好记性不如烂键盘</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-book">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            book
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://joewt.com/2018/02/04/std-IO/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="JOE">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/assets/img/favicon1.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JOE'S BLOG">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">标准I/O库(五)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-02-04T17:18:44+08:00">
                2018-02-04
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/UNIX环境高级编程/" itemprop="url" rel="index">
                    <span itemprop="name">UNIX环境高级编程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/02/04/std-IO/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2018/02/04/std-IO/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Words count in article&#58;</span>
                
                <span title="Words count in article">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Reading time &asymp;</span>
                
                <span title="Reading time">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>UNIX一切皆文件，掌握文件的操作尤其重要。以下的内容主要是apue上面第五章内容，介绍了标准I/O库的一些内容。</p>
<hr>
<h2 id="流和FILE对象"><a href="#流和FILE对象" class="headerlink" title="流和FILE对象"></a>流和FILE对象</h2><p>标准I/O库，他们的操作都是围绕流进行的<br>字符分为单字节和多字节，流的定向决定了是所读、写的字符是单字节还是多字节的。当一个流被创建时，并没有定向。使用多字节I/O函数，流的定向就被设置为宽定向，单字节同理。只有两个函数可以改变流的定向，freopen和fwide  </p>
<a id="more"></a>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">#include &lt;wchar.h&gt;</span><br><span class="line">int fwide(FILE *fp, int mode);</span><br><span class="line">//若流是宽定向的，返回正值；若流是单字节定向的返回负值，流未定向，返回0</span><br></pre></td></tr></table></figure>
<p>mode参数的说明  </p>
<ul>
<li>mode为负，fwide将使指定的流是单字节定向的</li>
<li>mode为正，fwide将使指定的流是宽定向的</li>
<li>mode为0，不设置流的定向，但返回标识该流定向的值</li>
</ul>
<hr>
<h2 id="缓冲"><a href="#缓冲" class="headerlink" title="缓冲"></a>缓冲</h2><p>标准I/O库提供缓冲的目的是尽可能减少read和write的调用。<br>标准I/O提供了3种缓冲</p>
<ol>
<li>全缓冲。只有填满标准I/O缓冲区后才进行实际的I/O操作。对于驻留在磁盘上的文件通常是由标准I/O库实施全缓冲的。在一个流上执行第一次I/O操作是，相关I/O函数通常调用malloc获得需要的缓冲。</li>
<li>行缓冲。当在输入输出中遇到换行符时，标准I/O库执行I/O操作。这允许我们一次输出一个字符(fputc),但只有在写了一行之后才进行实际的I/O操作。当涉及一个终端时(如标准输入和标准输出)，通常使用行缓冲。</li>
<li>不带缓冲。标准I/O库不对字符进行缓冲存储。例如，若用标准I/O函数fputs写15个字符到不带缓冲的流中，我们就期望这15个字符能立即输出，就很有可能使用write函数将这些字符写到相关联的打开文件中。</li>
</ol>
<p>标准错误流stderr通常是不带缓冲的。<br>ISO C要求下列缓冲特征</p>
<ul>
<li>当且仅当标准输入和标准输出并不指向交互设备时，他们才是全缓冲的</li>
<li>标准错误绝不是全缓冲的</li>
</ul>
<p>很多系统默认使用下列类型的缓冲</p>
<ul>
<li>标准错误是不带缓冲的</li>
<li>若是指向终端设备的流，则是行缓冲的；否则是全缓冲的</li>
</ul>
<p>如果不喜欢系统默认的可使用下列两个函数中的一个更改缓冲类型</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdiio.h&gt;</span><br><span class="line">void setbuf(FILE *restrict fp, char *restrict buf);</span><br><span class="line">int setvbuf(FILE *restrict fp, char *restrict buf, int mode, size_t size);</span><br></pre></td></tr></table></figure>
<p>在任何时候都可以强制冲洗一个流<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int fflush(FILE *fp);</span><br><span class="line">//成功返回0，失败返回EOF</span><br></pre></td></tr></table></figure></p>
<hr>
<h2 id="打开流"><a href="#打开流" class="headerlink" title="打开流"></a>打开流</h2><p>下列3个函数打开一个标准I/O流<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">FILE *fopen(const char *restrict pathname, const char *restrict type);</span><br><span class="line">FILE *freopen(const char *restrict pathname, const char *restrict type, FILE *restrict fp);</span><br><span class="line">FILE *fdopen(int fd, const char *type);</span><br><span class="line">//成功返回文件指针，失败返回NULL</span><br></pre></td></tr></table></figure></p>
<p>这3个函数区别如下</p>
<ol>
<li>fopen函数打开路径名为pathname的一个指定的文件</li>
<li>freopen函数在一个指定的流上打开一个指定的文件，如若该流已经打开，则先关闭该流。若流已经定向，则使用freopen清除定向。此函数一般用于将一个指定的文件打开为一个预定义的流：标准输入、标准输出或标准错误</li>
<li>fdopen函数取一个已有的文件描述符(我们可能从open、dup、dup2、fcntl、pipe、socket、socketpair或accept函数得到此文件描述符)，并使一个标准I/O流与该描述符相结合。此函数常用于由创建管道和网络通信通道函数返回的描述符。因为这些特殊类型文件不能使用标准I/O函数fopen打开，所以我们必须先调用设备专用函数以获得一个文件描述符，然后用fdopen使一个标准I/O流与该描述符相结合。</li>
</ol>
<p>fdopn是 POSIX.1 具有的</p>
<p>type参数说明如下</p>
<table>
<thead>
<tr>
<th style="text-align:left">type</th>
<th style="text-align:left">说明</th>
<th style="text-align:left">open(2)标志</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">r或rb</td>
<td style="text-align:left">为读而打开</td>
<td style="text-align:left">O_RDONLY</td>
</tr>
<tr>
<td style="text-align:left">w或wb</td>
<td style="text-align:left">把文件截断至0长，或为写而创建</td>
<td style="text-align:left">O_WRONLY</td>
<td>O_CREAT</td>
<td>O_TRUNC</td>
</tr>
<tr>
<td style="text-align:left">a或ab</td>
<td style="text-align:left">追加；为在文件尾而写打开，或为写而创建</td>
<td style="text-align:left">O_WRONLY</td>
<td>O_CREAT</td>
<td>O_APPEND</td>
</tr>
<tr>
<td style="text-align:left">r+或r+b或rb+</td>
<td style="text-align:left">为读和写打开</td>
<td style="text-align:left">O_RDWR</td>
</tr>
<tr>
<td style="text-align:left">w+或w+b或w+</td>
<td style="text-align:left">把文件截断为0长，或为读和写而打开</td>
<td style="text-align:left">O_RDWR</td>
<td>O_CREAT</td>
<td>O_TRUNC</td>
</tr>
<tr>
<td style="text-align:left">a+或a+b或ab+</td>
<td style="text-align:left">为在文件尾读和写而打开或创建</td>
<td style="text-align:left">O_RDWR</td>
<td>O_CREAT</td>
<td>O_APPEND</td>
</tr>
</tbody>
</table>
<hr>
<h2 id="读和写流"><a href="#读和写流" class="headerlink" title="读和写流"></a>读和写流</h2><p>一旦打开了流，则可在3种不同类型的非格式化I/O中进行选择，对其进行读、写操作  </p>
<ol>
<li>每次一个字符的I/O。一次读或写一个字符，如果流是带缓冲的，则标准I/O函数处理所有缓冲。</li>
<li>每次一行的I/O。如果想要一次读或写一行，则使用fgets和fputs。每行都以一个换行符终止。当调用fgets时，应说明能处理的最大行长。</li>
<li>直接I/O。fread和fwrite函数支持这种类型的I/O。每次I/O操作读或写某种数量对象，而每个对象具有指定的长度。这两个函数常用于从二进制文件中每次读或写一个结构。</li>
</ol>
<h4 id="1-输入函数"><a href="#1-输入函数" class="headerlink" title="1. 输入函数"></a>1. 输入函数</h4><p>以下三个函数可用于一次读一个字符<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int getc(FILE *fp);</span><br><span class="line">int fgetc(FILE *fp);</span><br><span class="line">int getchar(void);</span><br><span class="line">//成功返回下一个字符，失败或到达文件末尾，返回EOF</span><br></pre></td></tr></table></figure></p>
<p>函数getchar()等同于 getc(stdin)。getc可被实现为宏，fgetc不能。意味着以下几点</p>
<ol>
<li>getc的参数不应当是具有副作用的表达式，因此它可能会被计算多次</li>
<li>因为fgetc一定是一个函数，所以它可以得到地址。这就允许将fgetc的地址作为一个参数传递给另一个函数</li>
<li>调用fgetc所需时间很可能比调用getc要长，因为调用函数所需时间通常长于调用宏</li>
</ol>
<p>不管是出错还是到达文件尾端，这3个函数都返回同样的值。为了区分这两种不同的情况，必须调用ferror或feof。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int ferror(FILE *fp);</span><br><span class="line">int feof(FILE *fp);</span><br><span class="line">//两个函数的返回值，若成功返回非0(真)；否则返回0(假)</span><br><span class="line">void clearerr(FILE *fp);</span><br></pre></td></tr></table></figure></p>
<p>在大多数实现中，为每个流在FILE对象中维护了两个标志:</p>
<ul>
<li>出错标志</li>
<li>文件结束标志</li>
</ul>
<p>调用clearerr可以清除这两个标志。<br>从流中读取数据以后，可以调用ungetc将字符再压送回流中。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdiio.h&gt;</span><br><span class="line">int ungetc(int c,FILE *fp);</span><br><span class="line">//成功返回c，出错返回EOF</span><br></pre></td></tr></table></figure></p>
<h4 id="2-输出函数"><a href="#2-输出函数" class="headerlink" title="2. 输出函数"></a>2. 输出函数</h4><p>对应上面每个输入函数都有一个输出函数<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int putc(int c, FILE *fp);</span><br><span class="line">int fputc(int c, FILE *fp);</span><br><span class="line">int putchar(int c);</span><br><span class="line">//成功返回c，出错返回EOF</span><br></pre></td></tr></table></figure></p>
<hr>
<h2 id="每次一行I-O"><a href="#每次一行I-O" class="headerlink" title="每次一行I/O"></a>每次一行I/O</h2><p>下面两个函数提供每次输入一行的功能<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">char *fgets(char *restrict buf, int n, FILE *restrict fp);</span><br><span class="line">char *gets(char *buf);</span><br><span class="line">//成功返回buf；若已到达文件尾端或出错，返回NULL</span><br></pre></td></tr></table></figure></p>
<p>推荐使用fgets<br>每个输入都有对应的输出<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int fputs(const char* restrict str, FILE *restrict fp);</span><br><span class="line">int puts(const char *str);</span><br><span class="line">//成功返回非负值，失败返回EOF</span><br></pre></td></tr></table></figure></p>
<hr>
<h2 id="二进制I-O"><a href="#二进制I-O" class="headerlink" title="二进制I/O"></a>二进制I/O</h2><p>系统提供了以下函数执行二进制I/O操作<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);</span><br><span class="line">size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);</span><br><span class="line">//两个函数的返回值：读或写的对象数</span><br></pre></td></tr></table></figure></p>
<hr>
<h2 id="定位流"><a href="#定位流" class="headerlink" title="定位流"></a>定位流</h2><p>有3种方式定位标准I/O流  </p>
<ol>
<li>ftell和fseek函数。这俩函数都是假定文件的位置可以存放在一个长整数中</li>
<li>ftellofseeko函数。Single UNIX Specification引入了这两个函数，使文件偏移量可以不必一定使用长整形。他们使用off_t数据类型替代了长整形</li>
<li>fgetpos和fsetpos函数。这两个函数是由ISO C引入的。他们使用一个抽象数据类型fpos_t记录文件位置。这种数据类型可以根据需要定义一个足够大的数，用以记录文件位置。</li>
</ol>
<p>需要移植到非UNIX系统上需要使用fgetpos和fsetpos函数</p>
<hr>
<h2 id="格式化I-O"><a href="#格式化I-O" class="headerlink" title="格式化I/O"></a>格式化I/O</h2><p>格式化输出是由5个printf函数处理<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdio.h&gt;</span><br><span class="line">int printf(const char* restrict format, ...);</span><br><span class="line">int fprintf(FIFE *restrict fp, const char* restrict format, ...);</span><br><span class="line">int dprintf(int fd, const char* restrict format, ...);</span><br><span class="line">//若成功返回输出字符数。出错返回负值</span><br><span class="line">int sprintf(char* restrict buf, const char* restrict format, ...);</span><br><span class="line">//成功返回存入数组的字符数，若编码出错返回负值</span><br><span class="line">int snprintf(char* restrict buf, size_t n, const char* restrict format, ...);</span><br><span class="line">若缓冲区足够大，返回将要存入数组的字符数，若编码出错返回负值</span><br></pre></td></tr></table></figure></p>
<p>printf将格式化的数据写到标准输出，fprintf写至指定的流，dprintf写至指定的文件描述符，sprintf将格式化的字符送入数组buf中。sprintf在该数组的尾端自动加一个null字节，但该字符不包括在返回值中。  </p>
<h4 id="格式化输入"><a href="#格式化输入" class="headerlink" title="格式化输入"></a>格式化输入</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#incude &lt;stdio.h&gt;</span><br><span class="line">int scanf(const char* restrict format, ...);</span><br><span class="line">int fscanf(FIFE *restrict fp, const char* restrict format, ...);</span><br><span class="line">int sscanf(const char* restrict buf, const char* restrict format, ...);</span><br><span class="line">//3个函数的返回值，赋值的输入项数，若出错或任一转换前已到达文件尾端，返回EOF</span><br></pre></td></tr></table></figure>
<h2 id="临时文件"><a href="#临时文件" class="headerlink" title="临时文件"></a>临时文件</h2><p>ISO C标准I/O库提供了两个函数以帮助创建临时文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#include &lt;stdiio.h&gt;</span><br><span class="line">char *tmpnam(char *ptr);</span><br><span class="line">FILE *tmpfile(void);</span><br><span class="line">//成功返回文件指针，出错返回null</span><br></pre></td></tr></table></figure></p>
<p>tmpnam函数产生一个与现有文件名不同的一个有效路径名字符串。每次调用它时，都产生一个不同的路径名，最多调用次数是TMP_MAX(定义在<stdio.h>在mac系统该值为308915776)<br>若ptr是NULL，则所产生的路径名存放在一个静态区中，指向该静态区的指针作为函数值返回。后续调用tmpnam时，会重写该静态区(这意味着，如果我们调用此函数多次，而且想保存路径名，则我们应该保存该文件的副本，而不是指针的副本)。如若ptr不是NULL，则认为它应该是指向长度至少是L_tmpnam个字符的数组(L_tmpnam定义在<stdio.h>中mac下为1024)。所产生的路径名存放在该数组中，ptr也作为函数值返回。<br>tmpfile创建一个临时二进制文件(类型wb+)，在关闭该文件或程序结束时将自动删除这种文件。注意，UNIX对二进制文件不进行特殊区分。  </stdio.h></stdio.h></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>感谢土豪</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/assets/img/alipay.png" alt="JOE Alipay"/>
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>Post author:</strong>
    JOE
  </li>
  <li class="post-copyright-link">
    <strong>Post link:</strong>
    <a href="https://joewt.com/2018/02/04/std-IO/" title="标准I/O库(五)">https://joewt.com/2018/02/04/std-IO/</a>
  </li>
  <li class="post-copyright-license">
    <strong>Copyright Notice: </strong>
    All articles in this blog are licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> unless stating additionally.
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/UNIX/" rel="tag"># UNIX</a>
          
            <a href="/tags/C/" rel="tag"># C</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/03/python-mysql/" rel="next" title="python-mysql">
                <i class="fa fa-chevron-left"></i> python-mysql
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/08/Progress-env/" rel="prev" title="进程环境(七)">
                进程环境(七) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/assets/img/favicon1.png"
                alt="JOE" />
            
              <p class="site-author-name" itemprop="name">JOE</p>
              <p class="site-description motion-element" itemprop="description">爱生活，爱coding</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yinrenxin" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:joewttx@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://learnerwn.github.io" title="Murphy" target="_blank">Murphy</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://strcpy.me" title="virusdefender" target="_blank">virusdefender</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://qulongjun.com/" title="落苏" target="_blank">落苏</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tysb7.cn/" title="汤圆" target="_blank">汤圆</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://aconion.com" title="阿葱" target="_blank">阿葱</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://csy-anxuanxun.cn" title="csy" target="_blank">csy</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://hakana.cn" title="幻梦" target="_blank">幻梦</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.fastrun.cn" title="CrazyCodes" target="_blank">CrazyCodes</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.heanny.cn" title="Heanny" target="_blank">Heanny</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://vkkevin.xyz" title="Kevin" target="_blank">Kevin</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#流和FILE对象"><span class="nav-number">2.</span> <span class="nav-text">流和FILE对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缓冲"><span class="nav-number">3.</span> <span class="nav-text">缓冲</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#打开流"><span class="nav-number">4.</span> <span class="nav-text">打开流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#读和写流"><span class="nav-number">5.</span> <span class="nav-text">读和写流</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-输入函数"><span class="nav-number">5.0.1.</span> <span class="nav-text">1. 输入函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-输出函数"><span class="nav-number">5.0.2.</span> <span class="nav-text">2. 输出函数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#每次一行I-O"><span class="nav-number">6.</span> <span class="nav-text">每次一行I/O</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二进制I-O"><span class="nav-number">7.</span> <span class="nav-text">二进制I/O</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定位流"><span class="nav-number">8.</span> <span class="nav-text">定位流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#格式化I-O"><span class="nav-number">9.</span> <span class="nav-text">格式化I/O</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#格式化输入"><span class="nav-number">9.0.1.</span> <span class="nav-text">格式化输入</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#临时文件"><span class="nav-number">10.</span> <span class="nav-text">临时文件</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">JOE</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>








        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  








  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://billts.site/extra_css/gitment.css">
        <script src="https://billts.site/js/gitment.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'Joewt',
            repo: 'blogComment',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: 'aeba4f8f14a7d3464ef3ea9faef0d67409229e47',
            
                client_id: '12908903defa4c3347b8'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"left","width":75,"height":150},"mobile":{"show":true},"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script></body>
</html>
